package org.xinyin025.sinaweibodemo;

import java.io.IOException;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

/**
 * 发布一条文字微博
 * @author 蓝骑士(xinyin025)
 * @version 1.0
 */
public class SendMsg extends Activity implements View.OnClickListener,RequestListener {
	SharedPreferences pre;
	EditText msg_et;
	Button send_btn;
	Oauth2AccessToken access_token;
	StatusesAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_sendmsg);
		pre = getSharedPreferences("Setting", MODE_PRIVATE);
		initView();
		send_btn.setOnClickListener(this);
	}
	void initView(){
		msg_et= (EditText) findViewById(R.id.msg_et);
		send_btn = (Button) findViewById(R.id.send_btn);
	}
	@Override
	public void onComplete(String arg0) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SendMsg.this, "分享成功!", Toast.LENGTH_SHORT).show();
			}
		});
		SendMsg.this.finish();
	}
	@Override
	public void onError(WeiboException arg0) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SendMsg.this, "分享失败!", Toast.LENGTH_SHORT).show();
			}
		});
		SendMsg.this.finish();
		
	}
	@Override
	public void onIOException(IOException arg0) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SendMsg.this, "分享失败!", Toast.LENGTH_SHORT).show();
			}
		});
		SendMsg.this.finish();
		
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send_btn:
			access_token = new Oauth2AccessToken(pre.getString("token", ""), pre.getString("expires_in", "0"));
			StatusesAPI api = new StatusesAPI(access_token);
			String content = msg_et.getText().toString();
			if(TextUtils.isEmpty(content)){
				Toast.makeText(SendMsg.this, "请输入发布内容！", Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				/*
				 * 发布文字微博
				 */
				api.update(content, "0", "0", this);
			} catch (Exception e) {
			}
			break;

		default:
			break;
		}
	}
}
